"""
短信服务工具（容联云）
"""
import requests
import random
import hashlib
import base64
import json
from typing import Optional
from datetime import datetime
from config import settings


class RonglianSMS:
    """容联云短信服务"""
    
    def __init__(self):
        from config import settings
        # 容联云配置
        self.account_sid = settings.RONGLIAN_ACCOUNT_SID
        self.auth_token = settings.RONGLIAN_AUTH_TOKEN
        self.app_id = settings.RONGLIAN_APP_ID
        self.template_id = settings.RONGLIAN_TEMPLATE_ID
        self.base_url = "https://app.cloopen.com:8883"
    
    def _generate_signature(self, timestamp: str) -> str:
        """生成签名"""
        sig = f"{self.account_sid}{self.auth_token}{timestamp}"
        return hashlib.md5(sig.encode()).hexdigest().upper()
    
    def _get_authorization(self) -> str:
        """获取Authorization"""
        src = f"{self.account_sid}:{datetime.now().strftime('%Y%m%d%H%M%S')}"
        auth = base64.b64encode(src.encode()).decode()
        return auth
    
    def send_verification_code(self, phone: str, code: str) -> tuple[bool, str]:
        """
        发送验证码
        
        Args:
            phone: 手机号
            code: 验证码（6位数字）
        
        Returns:
            (是否成功, 错误信息)
        """
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
        signature = self._generate_signature(timestamp)
        authorization = base64.b64encode(f"{self.account_sid}:{timestamp}".encode()).decode()
        
        url = f"{self.base_url}/2013-12-26/Accounts/{self.account_sid}/SMS/TemplateSMS?sig={signature}"
        
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": authorization
        }
        
        data = {
            "to": phone,
            "appId": self.app_id,
            "templateId": self.template_id,
            "datas": [code, "5"]  # 验证码，有效期（分钟）
        }
        
        try:
            response = requests.post(
                url,
                headers=headers,
                json=data,
                timeout=10
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get("statusCode") == "000000":
                    return True, "发送成功"
                else:
                    return False, result.get("statusMsg", f"发送失败: {result}")
            else:
                return False, f"请求失败: HTTP {response.status_code} - {response.text}"
                
        except Exception as e:
            return False, f"发送异常: {str(e)}"
    
    @staticmethod
    def generate_code(length: int = 6) -> str:
        """生成验证码"""
        return ''.join([str(random.randint(0, 9)) for _ in range(length)])


# 创建全局实例
sms_client = RonglianSMS()

